var DESIGN_MODE = !true;

var curPage;

var curPageData;// = $.extend({}, pageData[curPage]);
var curKeySeq = "";
var validateKeySeq = "";
var seqLen;
var canTakeKeyDown = true;
var correctClick=false;
var incorrectMsg=false;
var isShowDropdown=false;
var isTextField=false;
var hideGlobalKey=false;
var isDropdownSeqLen;
var currentItem;
var incorrectAttempts=2;
var deadElementsInClick,deadElementsInKeys;
//var qaMode=false;

$(document).keydown(function(e) { //Should be the FIRST keydown handler
	
});

$(document).keydown(function(e) {
	if (!canTakeKeyDown && ((e.which==121 && !e.shiftKey) || e.which==18))return false;
	canTakeKeyDown = false;
	document.title = e.which;
	var curChar = String.fromCharCode(e.which);	
	if (e.which == 27) {
		curKeySeq = "";
	} else if (e.which == 16) {
		return;
	} else {
		if (curKeySeq=="" && e.which==121 && !e.shiftKey) curChar = String.fromCharCode(18);	
		curKeySeq += curChar;
		
	}
	
	//DISABLING BROWSER KEYS - CHROME
	if(e.which==72 && e.ctrlKey){console.log("testttttttttttst");incorrectMsg=true;return false;}
	
	//console.log(e.shiftKey+"in key down="+e.which)
	return handleKey(e);
});

$(document).keyup(function(e) {
	canTakeKeyDown = true;
	
	console.log(incorrectMsg+"=key up..."+e.which+"=isShowDropdown="+isShowDropdown+"=isShowRightClickMenu="+isShowRightClickMenu)
	if((isShowDropdown=="true" || isShowDropdown==true) && !isShowRightClickMenu){
		incorrectMsg=true;
		$("#glasscontainer").html('');
		console.log("in key up frame work...")
		
		doDropdownkeyHandler(e.which);
		
	}
	
	
	if(!incorrectMsg){
		console.log("call incorrect...")			
		if(!isTextField)
		doKeyWrongAction();
	}
	//isTextField=false;	
});

function handleKey(e) {
	var allowedKeys;
	var retVal = true;
	
	seqLen = curKeySeq.length;
	var matchCount = 0;
	var actionDone = false;
	$(".keypanel").remove();
	document.title = "";
	keysDisplayed = [];	
	console.log("handlekey="+seqLen)
	if (seqLen==1 && curKeySeq=='\x12' && !isShowDropdown && !isShowFileMenu) {
		retVal = false;
		incorrectMsg=true;
		for(var i in keyLevel1Action) {
			matchCount++;
			displayKey(i, keyLevel1Action[i], false);					
		}
		console.log("ALT...Pressed..."+incorrectMsg)
	} else {
		console.log("hhhhhhhhhhhhhhhhh="+hideGlobalKey)
		//this code is used to change the navigation image according to the selected tab
		if (seqLen==2 && curKeySeq.indexOf('\x12')==0) {			
			if (curKeySeq.substring(1,2) == "F")			
				fileMenuPreviousTab = curPage;
				
			if (keyLevel1Action[curKeySeq.substring(1,2)]){
				incorrectMsg=true;
				console.log("hellow--------"+keyLevel1Action[curKeySeq.substring(1,2)][4].substring(1))
				actionLoadPage(keyLevel1Action[curKeySeq.substring(1,2)][4].substring(1));
			}else{
				incorrectMsg=false;
			}
		} 
		
		//this code is used to change the navigation image according to the selected tab
		
		else if (seqLen==3 && curKeySeq.indexOf('\x12')==0 && curKeySeq.indexOf('F')==1) {		
			changeFileMenuTab(curKeySeq.substring(2,3));
		}
		//console.log("hhhhhhh"+seqLen+"---"+curKeySeq.indexOf('\x12')+"---"+curKeySeq.indexOf('F'))
		for(var i=0;i<keyData[curPage].length;i++) {
			
			if (keyData[curPage][i][4].indexOf(curKeySeq) == 0) {			
				retVal = false;				
				if (seqLen==1) {
					matchCount++;
					//NO USE: displayKey(keyData[curPage][i][4].substring(1,2), keyLevel1Action[keyData[curPage][i][4].substring(1,2)], false);
				} else if (keyData[curPage][i][4] == curKeySeq) {
					isDropdownSeqLen=seqLen;
					doKeyAction(e, curKeySeq);
					curKeySeq = "";					
					break;
				} else if (seqLen>1) {
					if (seqLen == 2 && !actionDone) {
						if(curKeySeq.substring(1,2) == "F") {
							actionDone = false;
						} else {
							actionDone = true;
						}
						
						$(keyLevel1Action[curKeySeq.substring(1,2)][4]).each(function(idx, item) {							
							doAction(item, false);
						});
					} else if (seqLen == 3 && !actionDone) {
						actionDone = true;
						$(keyLevel1Action[curKeySeq.substring(1,2)][4]).each(function(idx, item) {							
							doAction(item, false);
						});
					} else if(seqLen > 3 && isShowFileMenu == true) {
						if(fileMenuPageKey(curKeySeq) == true) {
							doAction(item, false);
						}
					}
					matchCount++;
					//console.log(isShowFileMenu+"cccccccccc="+keyData[curPage][i][4].substring(seqLen))
					if(isShowFileMenu){
						displayKey(keyData[curPage][i][4].substring(seqLen),keyData[curPage][i],(keyData[curPage][i][5]=='Y'));
					}else{
						 if(!hideGlobalKey)
						displayKey(keyData[curPage][i][4].substring(seqLen>2?2:seqLen),keyData[curPage][i],(keyData[curPage][i][5]=='Y'));					
					}
				}
			}
		}
		//console.log(e.shiftKey+"=ctrl="+e.which+"--5555555555555-"+isShowSubMenu+"---"+seqLen)
		//actionOffice(seqLen)
		if(isShowRightClickMenu && !isShowSubMenu){
			
			doRightClickKeyAction(e, e.which)
		}else if(isShowSubMenu){
			doRightClickSubMenuKeyAction(e.which)
		}
		else if(isShowFileMenu) {
			if(event.which == 37 || event.which == 38 || event.which == 39 || event.which == 40)
				doFileMenuKeyHandler(event.which)
			else 
				keyHandler(event.which,event.ctrlKey,event.shiftKey,event.altKey);
		}else {
			if(!isShowDropdown)
			keyHandler(e.which,e.ctrlKey,e.shiftKey,e.altKey);
		}
		if(isDropdownSeqLen==3 && isShowDropdown=="true"){
			for(var i in dropDownKeys) {
				//	matchCount++;
				displayKey(i, dropDownKeys[i], false);					
			}			
		}
		
	}
	if (matchCount==0) {
		if ('\x12\x79'.indexOf(curKeySeq.substring(curKeySeq.length-1))>-1) {
			retVal = false;			
			if(e.which==18)incorrectMsg=true;
		}
		curKeySeq = "";
	}
	globalDeadKeys(e.which,e.ctrlKey,e.shiftKey,e.altKey);
	incorrectMsg=true;
	if(e.shiftKey && e.which==121){doRightClickUsingKeys(e, $("#rightclickmenucontainer"));console.log("ssssss");incorrectMsg=true;}
	return retVal;
}

var keysDisplayed = [];

function doKeyWrongAction() {
	//console.log("Wrong key pressed"+incorrectMsg);
	showIncorrect();
}

function doKeyAction(e, keySeq) {
	console.log("in doKeyAction.."+incorrectMsg)
	keysDisplayed = [];
	$(".keypanel").remove();
	doAction(e,"a_"+keySeq, false);
}

function displayKey(text, pos, isDehighlight) {
	if (keysDisplayed.indexOf(text) > -1) return;
	keysDisplayed[keysDisplayed.length] = text;
	//console.log("in displayKeyddyyyy..."+text);
	var gCtrl=$("#glasscontainer")
	var newItem = $("<div class='keypanel' style='background-color:#404040;text-align:center;color:white;font-family:verdana;font-size:12px;position:absolute;left:"+pos[0]+"px;top:"+pos[1]+"px;width:20px;height:16px;cursor:default;'>"+text+"</div>");
	if (isDehighlight) newItem.css("opacity", "0.5");
	
	if(isShowDropdown){$("#questioncontainer").append(newItem)}else{
	gCtrl.append(newItem);}
}

function keyHandler(curKey,ctrlKey,shiftKey,altKey){
	console.log("keyHandler--"+curKey+"---"+seqLen);
	var correctKey,deadKey,nextPath;
	for(var i=0; i<questionHotspots.length;i++){
		if(currentSegment==questionHotspots[i].id){
			correctKey=questionHotspots[i].actions.keys.keyUp.correct
			deadKey=questionHotspots[i].actions.keys.keyUp.dead
			for(var j=0; j<correctKey.length; j++){
				//console.log("indtsk keysyyyyyyyyyyyyyy"+correctKey[j].ctrl+"=="+String(ctrlKey)+"&&"+ correctKey[j].shift +"=="+String(shiftKey)+"&&"+correctKey[j].alt+"=="+String(altKey) +"&&"+correctKey[j].seqLen+" == "+seqLen +"&&"+ correctKey[j].page +"=="+ curPage +"&& "+correctKey[j].rightClick +" &&"+ correctKey[j].code);
				
				if(correctKey[j].ctrl == String(ctrlKey) && correctKey[j].shift == String(shiftKey) && correctKey[j].alt == String(altKey) &&
				correctKey[j].seqLen == seqLen /*&& correctKey[j].page == curPage*/ && correctKey[j].rightClick== "false" && correctKey[j].code == curKey){
					nextPath=correctKey[j].nextPath;
					isShowDropdown=correctKey[j].dropDown;
					
					for(var k=0; k<questionData.length;k++){						
						if(nextPath == questionData[k].id){
							currentSegment=questionData[k].id;							
							incorrectMsg=true;
							loadSegments(questionData[k].path, questionData[k].size, questionData[k].id)
							break;
						}
					}
					break;
				}//else{incorrectMsg=false;}
			}
			
			for(var d=0;d<deadKey.length;d++){				
				//console.log("-check dead-"+deadKey[d].ctrl+" =="+String(ctrlKey)+"&&"+deadKey[d].shift+"== "+String(shiftKey)+"&&"+deadKey[d].alt+"== "+String(altKey)+" &&"+deadKey[d].seqLen +"== "+seqLen +"&& "+deadKey[d].page +"== "+curPage +"&&"+ deadKey[d].code +"== "+curKey);
				if(deadKey[d].ctrl == String(ctrlKey) && deadKey[d].shift == String(shiftKey) && deadKey[d].alt == String(altKey) &&
				deadKey[d].seqLen == seqLen /*&& deadKey[d].page == curPage*/ && deadKey[d].code == curKey){
					incorrectMsg=true;
					event.preventDefault();
				}
			}
			
			break;
		}
	}
	
}

function doClickAction(event, ctrl) {	
	console.log("in fw.js=click="+ctrl.id);
	currentItem=ctrl.id.substring(2);
	if(currentItem=="Pictures"){
		isShowDropdown = true;
		$("#glasscontainer").html('');
	}else if(ctrl.id=="m_FileTab"){
		fileMenuPreviousTab = curPage;
		isShowFileMenu=true;
		$("#questioncontainer").css({"z-index":"50"});
		$("#question").hide();
	}
	doAllAction(event, ctrl, 4);
}

function doOverAction(event, ctrl) {	
	//console.log("ctttl="+ctrl.id+"---"+isShowRightClickMenu)
	doAllAction(event, ctrl, 5);
}

function doOutAction(event, ctrl) {
	doAllAction(event, ctrl, 5, true);
}

function doRightClickAction(event, ctrl) {
	//doAllAction(event, ctrl, 6);
	actionOffice(event, ctrl);
}

function doAllAction(event, ctrl, idx, isActionRevert) {	
	//console.log(isShowRightClickMenu+"actionList in fjs="+isShowSubMenu)
	var actionList = curPageData.marks[ctrl.id][idx];
	
	for(var i=0;i<actionList.length;i++) {
		doAction(event, actionList[i], isActionRevert);
	}
}

function doAction(event, dataId, isActionRevert) {	
	console.log("in doAction...="+event)
	hideFileMenuTab(event, dataId);
	
	var actionType = dataId.substring(0,1);
	console.log("in doAction...="+actionType)
	
	if (actionType =='p') {
		actionLoadPage(dataId.substring(1)-0);
	} if (actionType =='a') {
		//validateKeySeq = dataId.substring(2);
		//validateKey();
		console.log("in clickn in do actions")
		actionOffice(event, dataId);
	} if ('hbBi'.indexOf(actionType) >= 0) {
		if (isActionRevert) {			
			$("#"+dataId).hide();
		} else {
			$("#"+dataId).show();
		}
	}
}

function actionOffice(event, actionId) {
	console.log("ACTION: "+actionId+"------"+event);	
	console.log(event.which+"-hello---"+event.type+"----"+event.target.id)	
	
	var exitPath,correctElement,deadElement;
	
	incorrectMsg=false;
	
	for(var i=0; i<questionHotspots.length;i++){
		if(currentSegment==questionHotspots[i].id){
			//console.log("=event.type="+event.type)
			if(event.type!="contextmenu"){
				correctElement=questionHotspots[i].actions.click.correct.iconName;
				deadElement=questionHotspots[i].actions.click.dead;			
				exitPath=questionHotspots[i].actions.click.correct.nextPath;
			}else{
				correctElement=questionHotspots[i].actions.rightClick.correct.iconName;
				deadElement=questionHotspots[i].actions.rightClick.dead;			
				exitPath=questionHotspots[i].actions.rightClick.correct.nextPath;
				incorrectMsg=true;
				
				if(correctElement==event.target.id.substring(2)){
				doRightClickHandler(event, $("#rightclickmenucontainer"));break;}
			}
				for(var j=0; j<correctElement.length; j++){					
					if(correctElement[j]==event.target.id.substring(2)){
						for(var k=0; k<questionData.length;k++){						
							if(exitPath[j] == questionData[k].id){
								currentSegment=questionData[k].id;
								incorrectMsg=true;
								loadSegments(questionData[k].path, questionData[k].size, questionData[k].id)
								break;
							}
						}					
						break;
					}	
				}
			

				for(var d=0;d<deadElement.length;d++){
					//console.log("deadElement="+deadElement[d]+"--tar--"+event.target.id.substring(2))
					if(deadElement[d]==event.target.id.substring(2)){incorrectMsg=true;break;}
				}
			
			break;
		}			
	}
	
	console.log("in actoffice"+isShowDropdown)	
	//if(!incorrectMsg&&event.type!="keydown")//showIncorrect();
}

var segmentId;
var nextPath;
var iSize;

function loadSegments(path, size, id){	
	nextPath=path;
	iSize=size;
	segmentId=id;		
	console.log("nextPath in ls="+segmentId.split('_')[1]+"=isShowFileMenu="+isShowFileMenu+"-isShowDropdown-"+isShowDropdown)
	if(!isShowFileMenu){
		
			if(iSize!="long"){
				$("#question")[0].src = nextPath;
				//$("#question").css({"left":"8px","top":"151px"});
				console.log("sssizzzzzzzzzzzzz")
			}else{
				//$("#question").remove();
				$("#questionImgLong")[0].src = nextPath;
				//$("#question").css({"left":"8px","top":"4px"});
				console.log("sssizzzzzzzzzzzzz-eeeeee")
			}	
		
		
		$("#questioncontainer").css({"z-index":"120"})
		if(segmentId.split('_')[1]=="RESULT"){endSimulation("1");}
	}else if(isShowFileMenu == true) {
		$("#questioncontainer").html('');
		$("#questioncontainer").css({"z-index":"1"})
	}else{
		$("#questioncontainer").html('');
		$("#questioncontainer").css({"z-index":"50"})
	}
	//$("#question").css({"left":"10px","top":"151px"})
	//if(isShowDropdown){$("#question").css({"left":"10p  x","top":"151px"});}else{$("#question").css({"left":"10px","top":"151px"})}
	if(isShowRightClickMenu){$("#rightclickmenu").hide();$("#rightclickmenucontainer").html('');}	
	loadQuestions($("#questioncontainer"),segmentId);	
}


function showIncorrect(){
	console.log("incorrectMsg in showinc=in if..="+incorrectMsg);
	if(!incorrectMsg){
		
		incorrectMsg=false;
		$("#incorrect").css("display","block");	
		$("#incorrect").fadeIn(1000, function() {
			timeout = setTimeout('hideIncorrect()', 1000);		
		});
		incorrectAttempts--;
		checkScore()
	}else{
		console.log("incorrectMsg in showinc=in else..="+incorrectMsg);
		incorrectMsg=false;
	}
}

function hideIncorrect() {
	$("#incorrect").fadeOut(1000, function() {
		$("#incorrect").css("display","none");
		clearTimeout(timeout);
	});
}

function actionLoadPage(pageIdx) {	
	
	if (pageIdx < pageData.length) {
		curPage = pageIdx;
		curPageData = $.extend({}, pageData[curPage]);
		
		if(curPage >= 8 && curPage <= 19) {
			$("#question").hide();
			isShowFileMenu = true;
		} else {
			$("#question").show();
			isShowFileMenu = false;
		}
		
		$("#headercontainer")[0].src = curPageData.headerimg;
		loadPageData();
		$("#incorrect")[0].src = '../images/incorrectMessage.png';				
		
	}
	
}

function loadPageData() {	
	var i, actionType, curItem, newItem, gCtrl=$("#glasscontainer"), hCtrl=$("#headercontainer");
	
	gCtrl.html("");
	setTimeout(function() {
		gCtrl.css({left:hCtrl.position().left, top:hCtrl.position().top, width:hCtrl.width(), height:hCtrl.height()});
	}, 100);   
	
	for(i in curPageData.htmls) {
		curItem = curPageData.htmls[i];
		newItem = $(curItem[4]);
		newItem.css({
						position:"absolute",
						border: "0px",
						//"z-index": 9,
						left: curItem[0]+"px",
						top: curItem[1]+"px",
						width: (curItem[2] - curItem[0])+"px",
						height: (curItem[3] - curItem[1])+"px"
		});
		gCtrl.append(newItem);
	}
	
	for(i in curPageData.marks) {
		curItem = curPageData.marks[i];
		
		newItem = $("<div></div>");
		newItem.attr("id", i);
		if (!DESIGN_MODE) {
			newItem.attr("onclick", "doClickAction(event, this);correctClick=true;");
			newItem.attr("onmouseover", "doOverAction(event, this)");
			newItem.attr("onmouseout", "doOutAction(event, this)");
			newItem.attr("oncontextmenu", "doRightClickAction(event, this)");
		} else {
			newItem.attr("title", i);
		}
		newItem.css({
						border:(DESIGN_MODE?"1px solid blue":"0px"),
						position:"absolute",
						"z-index": 99,
						left: curItem[0]+"px",
						top: curItem[1]+"px",
						width: (curItem[2] - curItem[0])+"px",
						height: (curItem[3] - curItem[1])+"px"
		});
		
		applyMouseCursor(newItem, i);
		gCtrl.append(newItem);
	};
	for(i in curPageData.action) {
		actionType = i.substring(0,1);
		
		if ('i'.indexOf(actionType)>=0) {
			curItem = curPageData.action[i];
			newItem = $('<img src="'+curItem[4]+'"></img>');
			newItem.attr("id", i);
			newItem.css({
							display: "none",
							position:"absolute",
							left: curItem[0]+"px",
							top: curItem[1]+"px"
			});
			gCtrl.append(newItem);
		} else if ('hbB'.indexOf(actionType)>=0) {
			curItem = curPageData.action[i];
			newItem = $("<div></div>");
			newItem.attr("id", i);
			newItem.css({
							display: "none",
							"background-color":(actionType=='h'?"LightSteelBlue":""),
							border:(actionType=='b'?"1px solid lightblue":(actionType=='B'?"4px solid LightSteelBlue":"0px")),
							'box-sizing': 'border-box',
							opacity: 0.5,
							position:"absolute",
							left: curItem[0]+"px",
							top: curItem[1]+"px",
							width: (curItem[2] - curItem[0])+"px",
							height: (curItem[3] - curItem[1])+"px"
			});
			gCtrl.append(newItem);
		}
	};
	loadSegments(questionData[0].path,questionData[0].size,currentSegment);
}



function globalDeadEvents(event){
	deadElementsInClick = globalJSON.hotspots.click.dead;
	for(var i=0;i<deadElementsInClick.length; i++){
		if(deadElementsInClick[i].name == event.target.id.substring(2)){
			incorrectMsg=true;
			break;
		}/*else{
			//incorrectMsg=false;
		}*/
	}
}

function applyMouseCursor(item, id) {
	if(	id == "m_FileNewBusiness" ||
		id == "m_FileNewPersonel" ||
		id == "m_FileNewIndustry" ||
		id == "m_FileNewPrint" ||
		id == "m_FileNewDesignSets" ||
		id == "m_FileNewEvent" ||
		id == "m_FileNewEducation") {
			item.css ({cursor: "pointer"});
		}
}

function globalDeadKeys(curKey,ctrlKey,shiftKey,altKey){
	deadElementsInKeys = globalJSON.keys.keyUp.dead;
	//console.log("in golabl.keys="+ctrlKey);	
	for(var i=0;i<deadElementsInKeys.length; i++){
		if(deadElementsInKeys[i].code == curKey && deadElementsInKeys[i].ctrl == String(ctrlKey) && deadElementsInKeys[i].shift == String(shiftKey) && deadElementsInKeys[i].alt == String(altKey)){
			incorrectMsg=true;
			break;
		}else{
			//incorrectMsg=false;
		}
	}
}

function actionLoadFileSubMenu(curKeySeq) {
	console.log("actionLoadFileSubMenu...")
	curPageData = $.extend({}, pageData[curPage]);
	keyDataTemp = keyData[curPage];
	for(var i=0; i < keyDataTemp.length; i++) {
		if(curKeySeq == keyDataTemp[i][4]) {
			selectedTabData = keyDataTemp[i];
			break;
		}
	}
	
	//$("#filemenu")[0].src = selectedTabData[6]["image"];
}

function endSimulation(score){
	var qaMode = globalJSON.qaMode.enabled;
	if(qaMode == "false"){
		setTimeout(function() {
			parent.handleHtmlResults(score)
		}, 1000);
		
	}
}

function checkScore(){
	var qaMode = globalJSON.qaMode.enabled;
	console.log("-end-"+qaMode)
	if(qaMode=="false"){
		
		if(incorrectAttempts<=0){
			console.log("in.........")
			endSimulation("0");
		}		
	}
}

function initApp(ctrl,curTab) {
	var strHtmlText = "";
	curPage=curTab;
	strHtmlText += '<img id="headercontainer" style="position:absolute;display:block;left:0px;top:0px;xborder:1px solid blue;"></img>';
	strHtmlText += '<img id="incorrect" style="position:absolute;display:none;z-index:9999;left:0px;top:0px;"></img>';
	strHtmlText += '<div id="glasscontainer" style="position:absolute;z-index:100;left:0px;top:0px;width:1200px;height:500px;box-sizing:border-box;xborder:1px solid red;"></div>';
	strHtmlText += '<img id="question" style="display:block;position:absolute;left:0px;top:143px;z-index:90;"></img>';
	strHtmlText += '<img id="questionImgLong" style="display:block;position:absolute;left:0px;top:0px;z-index:95;"></img>';
	strHtmlText += '<div id="questioncontainer" style="display:block;position:absolute;z-index:120;left:0px;top:143px;width:940px;height:467px;box-sizing:xborder-box;xborder:1px solid red;"></div>';
	strHtmlText += '<img id="rightclickmenu" style="position:absolute;display:block;z-index:130;"></img>';
	strHtmlText += '<div id="rightclickmenucontainer" style="position:absolute;display:block;z-index:140;box-sizing:border-box;xborder:1px solid blue;"></div>';
	strHtmlText += '<div id="submenucontainer" style="position:absolute;display:block;z-index:160;box-sizing:border-box;xborder:1px solid blue;"></div>';
	strHtmlText += '<img id="submenu" style="position:absolute;display:block;z-index:150;"></img>';
	ctrl.html(strHtmlText);	
	if (DESIGN_MODE) {
		$("#glasscontainer").click(function(e) {
			alert(e.offsetX+", "+e.offsetY);			
		});
	}
	$("#glasscontainer,#questioncontainer,#rightclickmenucontainer,#submenucontainer").click(function(e) {
		if (!correctClick) {			
			console.log("WRONG CLICK");
			//showIncorrect();
		}
		globalDeadEvents(e);
		
		showIncorrect();
		correctClick=false;
		console.log("in fw.js="+e.offsetX+"---"+e.offsetY+"=id="+e.target.id)		
	});
	$(document).bind("contextmenu",function(e){
		return false;			
	});	
	actionLoadPage(curPage);
	//parent.handleSimOkClick(1);
}

